/**
 * 游戏主类
 * 负责协调所有游戏组件和处理游戏循环
 */
class Game {
    constructor() {
        this.canvas = document.getElementById('gameCanvas');
        this.ctx = this.canvas.getContext('2d');
        
        this.cellSize = 20;
        this.gridWidth = Math.ceil(this.canvas.width / this.cellSize);
        this.gridHeight = Math.ceil(this.canvas.height / this.cellSize);
        
        const startX = this.cellSize / 2;
        const startY = this.cellSize / 2;
        this.player = new Player(startX, startY, 5);
        this.monsters = [
            new Monster(this.canvas.width / 4, this.canvas.height / 4),
            new Monster(this.canvas.width * 3/4, this.canvas.height / 4),
            new Monster(this.canvas.width / 2, this.canvas.height * 3/4)
        ];
        this.food = new Food(this.cellSize);
        this.astar = new AStar();
        
        this.foodCount = 0;
        this.deathCount = 0;
        this.totalAttempts = 0;
        
        this.isGameOver = false;
        this.setupEventListeners();
        this.updatePath();
        this.gameLoop();
    }

    setupEventListeners() {
        document.getElementById('restartBtn').addEventListener('click', () => {
            this.restart();
        });
    }

    updatePath() {
        const grid = this.createGrid();
        const start = {
            x: Math.floor(this.player.x / this.cellSize),
            y: Math.floor(this.player.y / this.cellSize)
        };
        const end = {
            x: Math.floor(this.food.x / this.cellSize),
            y: Math.floor(this.food.y / this.cellSize)
        };

        // 检查起点和终点是否相同
        if (start.x === end.x && start.y === end.y) {
            return;
        }

        // 检查起点和终点是否在安全区域
        if (grid[start.y][start.x] === 1 || grid[end.y][end.x] === 1) {
            this.player.setPath([]);
            return;
        }

        const path = this.astar.findPath(start, end, grid);
        
        if (path && path.length > 0) {
            // 只在路径发生实质变化时更新
            if (!this.player.path.length || 
                path[path.length - 1].x !== this.player.path[this.player.path.length - 1]?.x ||
                path[path.length - 1].y !== this.player.path[this.player.path.length - 1]?.y) {
                this.player.setPath(path);
            }
        } else {
            this.player.setPath([]);
        }
    }

    createGrid() {
        const grid = Array(this.gridHeight).fill().map(() => Array(this.gridWidth).fill(0));
        
        // 将怪物位置及其周围一定范围标记为障碍物，创建更大的安全区域
        this.monsters.forEach(monster => {
            // 减小安全半径，但保持足够的安全距离
            const safetyRadius = Math.ceil((monster.radius + this.cellSize * 2) / this.cellSize);
            const centerX = Math.floor(monster.x / this.cellSize);
            const centerY = Math.floor(monster.y / this.cellSize);
            
            for (let dy = -safetyRadius; dy <= safetyRadius; dy++) {
                for (let dx = -safetyRadius; dx <= safetyRadius; dx++) {
                    const x = centerX + dx;
                    const y = centerY + dy;
                    
                    if (x >= 0 && x < this.gridWidth && y >= 0 && y < this.gridHeight) {
                        // 使用更精确的圆形安全区域计算
                        const distance = Math.sqrt(dx * dx + dy * dy) * this.cellSize;
                        if (distance <= monster.radius + this.cellSize * 1.5) {
                            grid[y][x] = 1;
                        }
                    }
                }
            }
        });
        
        return grid;
    }

    checkCollisions() {
        // 检查是否吃到食物
        const distToFood = Math.hypot(this.player.x - this.food.x, this.player.y - this.food.y);
        if (distToFood < (this.player.radius + this.food.radius + 1)) {
            this.foodCount++;
            this.food.respawn(this.canvas.width, this.canvas.height);
            this.updatePath();
            this.updateStats();
        }

        // 检查是否碰到怪物，使用更精确的碰撞检测
        for (const monster of this.monsters) {
            const dx = this.player.x - monster.x;
            const dy = this.player.y - monster.y;
            const distance = Math.sqrt(dx * dx + dy * dy);
            
            // 使用实际的物理半径进行碰撞检测，只添加很小的容错
            const collisionDistance = this.player.radius + monster.radius + 2;
            
            if (distance < collisionDistance) {
                // 在判定碰撞前，再次确认距离，避免边缘情况
                const preciseDistance = Math.hypot(
                    this.player.x - monster.x,
                    this.player.y - monster.y
                );
                
                if (preciseDistance < collisionDistance) {
                    this.gameOver();
                    break;
                }
            }
        }
    }

    updateStats() {
        document.getElementById('foodCount').textContent = this.foodCount;
        document.getElementById('deathCount').textContent = this.deathCount;
        const survivalRate = this.totalAttempts === 0 ? 100 : 
            ((this.foodCount / (this.foodCount + this.deathCount)) * 100).toFixed(1);
        document.getElementById('survivalRate').textContent = survivalRate + '%';
    }

    gameOver() {
        this.isGameOver = true;
        this.deathCount++;
        this.totalAttempts++;
        this.updateStats();
        document.getElementById('finalScore').textContent = this.foodCount;
        document.getElementById('gameOver').style.display = 'block';
    }

    restart() {
        this.player = new Player(this.cellSize / 2, this.cellSize / 2, 5);
        this.monsters = [
            new Monster(this.canvas.width / 4, this.canvas.height / 4),
            new Monster(this.canvas.width * 3/4, this.canvas.height / 4),
            new Monster(this.canvas.width / 2, this.canvas.height * 3/4)
        ];
        this.food.respawn(this.canvas.width, this.canvas.height);
        this.isGameOver = false;
        document.getElementById('gameOver').style.display = 'none';
        this.updatePath();
    }

    isPathSafe() {
        if (!this.player.path.length) return true;

        for (let i = this.player.currentPathIndex; i < this.player.path.length; i++) {
            const pathPoint = this.player.path[i];
            
            for (const monster of this.monsters) {
                const pointX = pathPoint.x * this.cellSize + this.cellSize / 2;
                const pointY = pathPoint.y * this.cellSize + this.cellSize / 2;
                
                const dx = pointX - monster.x;
                const dy = pointY - monster.y;
                const distance = Math.sqrt(dx * dx + dy * dy);
                
                // 减小安全距离，但保持合理的避让空间
                const safeDistance = monster.radius + this.cellSize * 1.5;
                if (distance < safeDistance) {
                    return false;
                }
            }
        }
        return true;
    }

    update() {
        if (this.isGameOver) return;

        // 更新怪物位置
        this.monsters.forEach(monster => {
            monster.update(this.canvas.width, this.canvas.height);
        });

        // 更新玩家位置
        this.player.update();

        // 每帧都检查路径安全性
        if (!this.isPathSafe()) {
            this.updatePath();
        }
        // 如果没有路径，也更新路径
        else if (!this.player.path.length) {
            this.updatePath();
        }

        this.checkCollisions();
    }

    draw() {
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        
        this.ctx.strokeStyle = '#EEEEEE';
        for (let x = 0; x < this.gridWidth; x++) {
            for (let y = 0; y < this.gridHeight; y++) {
                this.ctx.strokeRect(
                    x * this.cellSize,
                    y * this.cellSize,
                    this.cellSize,
                    this.cellSize
                );
            }
        }

        this.food.draw(this.ctx);
        this.monsters.forEach(monster => monster.draw(this.ctx));
        this.player.draw(this.ctx);
    }

    gameLoop() {
        this.update();
        this.draw();
        requestAnimationFrame(() => this.gameLoop());
    }
}

window.onload = () => {
    new Game();
}; 